package org.fast.cms.service.admin.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.fast.cms.domain.admin.response.menu.Menu;
import org.fast.cms.entity.admin.SysMenu;
import org.fast.cms.persistent.mapper.common.SystemCommonMapper;
import org.fast.cms.service.admin.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/** 
* @author weigen.ye 
* @date 创建时间：2017年6月17日 下午2:33:19 
*
*/
@Service
public class SysMenuServiceImpl implements SysMenuService{

	 @Autowired
	 private SystemCommonMapper sysComMapper;
	 
	/**
     * 数据库Menu转换为Tree
     * @param menuList
     * @return
     */
    public List<Menu> getMenuTree(List<SysMenu> menuList) {
        Map<Integer, List<Menu>> mapMenu = Maps.newLinkedHashMap();
        for (SysMenu m : menuList) {
        	List<Menu> lisChildMenu = null;
        	if (mapMenu.containsKey(m.getParentMenuCode())) {
        		lisChildMenu = mapMenu.get(m.getParentMenuCode());	
        	} else {
				lisChildMenu = Lists.newArrayList();
			}
        	lisChildMenu.add(convertMenu(m));
        	mapMenu.put(m.getParentMenuCode(), lisChildMenu);
        }
        List<Menu> lisRootMenu = mapMenu.get(0);
        if (lisRootMenu != null) {
			for (Menu m : lisRootMenu) {
				addChild(m, mapMenu);
			}
		} else {
			lisRootMenu = Lists.newArrayList();
		}
        //没有二级目录时不展示一级目录
		for (int i = lisRootMenu.size() -1; i >= 0; i--) {
			Menu m = lisRootMenu.get(i);
            if (m.getChildMenu() == null || m.getChildMenu().size() == 0) {
                lisRootMenu.remove(m);
            }
        }
        return lisRootMenu;
    }
    
    @Override
	public List<SysMenu> getMenuActionByUserId(Integer userId) {
    	 return sysComMapper.getMenuActionByUserId(userId);
	}
    
    @Override
	public List<SysMenu> getAllMenuAction() {
		return sysComMapper.getAllMenuAction();
	}
    
    private Menu convertMenu(SysMenu m) {
        Menu ret = new Menu();
        ret.setMenuCode(m.getMenuCode());
        ret.setMenuName(m.getMenuName());
        ret.setIcon(m.getIcon());
        ret.setHref(m.getHref());
        ret.setDisplayFalg(m.getDisplayFlag());
        ret.setPermission(m.getPermission());
        return ret;
    }
    
    /**
	 * @param root
	 * @param mapMenu
	 */
	private void addChild(Menu root, Map<Integer, List<Menu>> mapMenu) {
		if (!mapMenu.containsKey(root.getMenuCode())) return;
		List<Menu> lisSysMenu = mapMenu.get(root.getMenuCode());
		root.setChildMenu(new ArrayList<Menu>());
		for (Menu m : lisSysMenu) {
			root.getChildMenu().add(m);
			addChild(m, mapMenu);
		}
	}

}
